﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Csharp.Events {
    
    /// <summary>
    /// An interpretation of Jeffrey Richter's MailManager example
    /// CLR through C# (p. 236)
    /// </summary>
    public class ExplicitlyControlling {
        // Private instance field serving as thread synchronization lock
        readonly object _eventLock = new object();

        // Private field that refers to the head of the delegate list
        EventHandler _handler;

        // Event member
        public event EventHandler Handler {
            add {
                lock (_eventLock)
                    _handler += value;
            }

            remove {
                lock (_eventLock)
                    _handler -= value;
            }
        }

        protected virtual void OnHandler(EventArgs e) {
            // Save the delegate field in a temporary field for thread safety
            EventHandler handler = _handler;
            if (handler != null)
                handler(this, e);
        }

        public static void Run(EventHandler handler) {
            ExplicitlyControlling example = new ExplicitlyControlling();
            example.Handler += handler;
            example.OnHandler(EventArgs.Empty);
        }
    }
}
